//发货单登记

interface IOrderRegisterViewModel extends IBaseViewModel<IOrderRegisterQueryTerms> {
    /**
     * ui-grid控制
     */
    gridOptions: uiGrid.IGridOptionsOf<carryOrderListResponse>;
    /**
     * 时间日期格式
     */
    dateFormat: "{format:'YYYY.MM.DD HH:mm'}";
    /**
     * 设置列表高度
     */
    heightA:number;
    /**
     * 合同状态下拉
     */
    contractStatusDropDown: ValueListItemResponse[];
    /**
     * 订单状态下拉
     */
    orderStatusDropDown: ValueListItemResponse[];
    /**
     * 油卡状态下拉
     */
    oilCardStatusDropDown: ValueListItemResponse[];
    /**
     * 回单状态下拉
     */
    receiptPriceStatusDropDown: ValueListItemResponse[];
    /**
     * 已选择的发货单id
     */
    id:string;
    /**
     * 已选择的发货单
     */
    orderInfoList: carryOrderListResponse;
    /**
     * 发货单登记事件
     */
    orderRegister: () => void;
    /**
     * 应收登记事件
     */
    getRegister: () => void;
    /**
     * 费用申领事件
     */
    costAplly: () => void;
    /**
     * 是否定位
     */
    carlocation:boolean;
    /**
     * 定位跟踪事件
     */
    carLbs: () => void;
}

/**
 * 查询条件
 */
interface IOrderRegisterQueryTerms {
    /**
     * 订单编号
     */
    orderId: string;
    /**
     * 客户单位
     */
    clientName: string;
    /**
     * 线路地址
     */
    route: string;
    /**
     * 合同号
     */
    contractNumber: string;
    /**
     * 发货起始时间
     */
    shipStartTime: string;
    /**
     * 发货结束时间
     */
    shipEndTime: string;
    /**
     * 车牌号
     */
    carCode: string;
    /**
     * 合同状态
     */
    contractStatus: string;
    /**
     * 订单状态
     */
    orderStatus: string;
    /**
     * 油卡状态
     */
    oilCardStatus: string;
    /**
     * 发货地址
     */
    shipAddress: string;
    /**
     * 送货地址
     */
    deliverAddress: string;
    /**
     * 回单状态
     */
    receiptPriceStatus: string;
    /**
     * 驾驶员姓名
     */
    driverName: string;
}

class OrderRegisterController extends ListController<IOrderRegisterViewModel, IOrderRegisterQueryTerms>{
    gridApi: uiGrid.IGridApiOf<carryOrderListResponse>;
    orderBy: number = 4;
    asc: boolean = false;
    /**
     * 订单状态
     */
    orderStatus:string;
    /**
     * 临时客服专员
     */
    TempCustomerServiceOfficerId:string;

    constructor($scope: IOrderRegisterViewModel, private valueService: IValueService, private orderService: IorderService, private $state: angular.ui.IStateService, private $ngBootbox: BootboxService,private $location:ng.ILocationService) {
        super($scope);
        this.init();
    }

    init(): void {
        super.init();

        this.$scope.id = "";
        this.$scope.carlocation = true;
        this.$scope.orderRegister = this.orderRegister;
        this.$scope.getRegister = this.getRegister;
        this.$scope.costAplly = this.costAplly;
        this.$scope.carLbs = this.carLbs;
        this.$scope.$on("WildDog:Order15", this.onWilddogOrderEvent);
        /**
         * 临时客服
         */
        if (window.localStorage.getItem("loginData").toString()) {
            this.TempCustomerServiceOfficerId = JSON.parse(window.localStorage.getItem("loginData").toString()).id;//临时客服
        } else {
            this.TempCustomerServiceOfficerId = "";//临时客服
        };

        $('#openTime').click(function () {
            $('#shipStartTime').datetimepicker('show');
        });
        $('#openEndTime').click(function () {
            $('#shipEndTime').datetimepicker('show');
        });

        this.$scope.queryTerms = {
            orderId: "",
            clientName: "",
            route: "",
            contractNumber: "",
            shipStartTime: "",
            shipEndTime: "",
            carCode: "",
            contractStatus: "",
            orderStatus: "",
            oilCardStatus: "",
            shipAddress: "",
            deliverAddress: "",
            receiptPriceStatus: "",
            driverName: "",
        }

        this.$scope.gridOptions = {
            multiSelect:false,
            enableRowSelection: true,
            enableRowHeaderSelection: false,
            enableSelectAll: false,
            paginationPageSizes: [10, 20, 45],
            useExternalPagination: true,
            useExternalSorting: true,
            enableColumnResizing: true,
            columnDefs: [
                { displayName: "订单编号", field: 'orderId', cellTemplate: '<div  ng-repeat="item in row.entity.orderList" class="LTL-list">{{item.orderId}}</div>', enableColumnMenu: false, cellTooltip: true, headerTooltip: true, width: '9%' },
                { displayName: "客户单位", field: 'clientName', cellTemplate: '<div  ng-repeat="item in row.entity.orderList" class="LTL-list">{{item.clientName}}</div>', enableColumnMenu: false, cellTooltip: true, headerTooltip: true, width: '10%' },
                { displayName: "发货地址", field: 'startAddress', cellTemplate: '<div  ng-repeat="item in row.entity.orderList" class="LTL-list">{{item.startAddress}}</div>', enableColumnMenu: false, cellTooltip: true, headerTooltip: true, width: '10%' },
                { displayName: '送货地址', field: 'endAddress', cellTemplate: '<div  ng-repeat="item in row.entity.orderList" class="LTL-list">{{item.endAddress}}</div>', enableColumnMenu: false, cellTooltip: true, headerTooltip: true, width: '10%' },
                { displayName: '发货时间', field: 'shipTime', cellTemplate: '<div  ng-repeat="item in row.entity.orderList" class="LTL-list">{{item.shipTime}}</div>', enableColumnMenu: false, cellTooltip: true, headerTooltip: true, width: '7%' },
                { displayName: '承运车牌号', field: 'carryCarCode', cellTemplate: '<div style="height:{{39 * row.entity.orderList.length}}px;" class="single-list">{{row.entity.carryCarCode}}</div>', enableColumnMenu: false, cellTooltip: true, headerTooltip: true },
                { displayName: '驾驶员姓名', field: 'driver', cellTemplate: '<div style="height:{{39 * row.entity.orderList.length}}px;"class="single-list">{{row.entity.driver}}</div>', enableColumnMenu: false, cellTooltip: true, headerTooltip: true },
                { displayName: '合同号', field: 'contractNum', cellTemplate: '<div style="height:{{39 * row.entity.orderList.length}}px;"class="single-list">{{row.entity.contractNum}}</div>', enableColumnMenu: false, cellTooltip: true, headerTooltip: true, },
                { displayName: '合同状态', field: 'contractStatus', cellTemplate: '<div style="height:{{39 * row.entity.orderList.length}}px;"class="single-list">{{row.entity.contractStatus}}</div>', enableColumnMenu: false, cellTooltip: true, headerTooltip: true, },
                { displayName: '油卡状态', field: 'oilCardStatus', cellTemplate: '<div style="height:{{39 * row.entity.orderList.length}}px;"class="single-list">{{row.entity.oilCardStatus}}</div>', enableColumnMenu: false, cellTooltip: true, headerTooltip: true, },
                { displayName: '回单状态', field: 'receiptStatus', cellTemplate: '<div  ng-repeat="item in row.entity.orderList" class="LTL-list">{{item.receiptStatus}}</div>', enableColumnMenu: false, cellTooltip: true, headerTooltip: true, },
                { displayName: '订单状态', field: 'orderStatus', cellTemplate: '<div ng-repeat="item in row.entity.orderList" class="LTL-list">{{item.orderStatus}}</div>', enableColumnMenu: false, cellTooltip: true, headerTooltip: true },
            ],
            onRegisterApi: (gridApi) => {
                this.gridApi = gridApi;
                if(window.localStorage.getItem(String(this.$state.current.url+'Page'))){
                        this.$scope.gridOptions.paginationCurrentPage=this.paginationOptions.currentPage;
                };
                 gridApi.pagination.on.paginationChanged(this.$scope,(skipSize,pageSize)=>{
                        this.paginationChanged(skipSize,pageSize,this.$state);
                });
                gridApi.core.notifyDataChange("options");
                gridApi.core.on.sortChanged(this.$scope, this.sortChange);
                gridApi.selection.on.rowSelectionChanged(this.$scope, this.selectChange);
            }
        };
        this.query();
        this.loadStatusDropDown();
    }

    localHistory():void{
        super.localHistory(this.$state);
    }
    getHistory():void{
        super.getHistory(this.$state,this.$location)
    }

    /**
     * 加载数据
     */
    loadData(queryTerms: IOrderRegisterQueryTerms, skip: number, count: number): void {
        if(queryTerms.orderStatus == "" || queryTerms.orderStatus == undefined || queryTerms.orderStatus ==null){
            this.orderStatus = "5,6,7";
        }
        else{
            this.orderStatus = queryTerms.orderStatus;
        }
        this.orderService.carryOrderList(this.orderBy.toString(), this.asc, queryTerms.orderId, queryTerms.clientName, queryTerms.route, queryTerms.shipStartTime,
            queryTerms.shipEndTime,this.orderStatus, "", "", queryTerms.shipAddress, queryTerms.deliverAddress, queryTerms.carCode, queryTerms.contractNumber,
            queryTerms.contractStatus, queryTerms.receiptPriceStatus, queryTerms.oilCardStatus, "", this.TempCustomerServiceOfficerId, "", "", "", queryTerms.driverName, "","","","","",skip, count).then(result => {
                // this.$scope.gridOptions.totalItems = result.data.total;
                this.$scope.gridOptions.data = result.data.data;
                /**
                 * 设置列表高度
                 */
                let gridHArr = 0;
                result.data.data.forEach((item,index) => { gridHArr =  gridHArr + item.orderList.length; });
                this.$scope.heightA = (gridHArr*39)+96;
                
                // if (skip == 0) {
                //     this.$scope.gridOptions.paginationCurrentPage = 1;
                // }
                this.$scope.querying = false;
            }, error => {
                this.$scope.querying = false;
            });
    }

    getListCount():void{
        if(this.$scope.queryTerms.orderStatus == "" || this.$scope.queryTerms.orderStatus == undefined || this.$scope.queryTerms.orderStatus ==null){
            this.orderStatus = "5,6,7";
        }
        else{
            this.orderStatus = this.$scope.queryTerms.orderStatus;
        }
        this.orderService.carrierOrderCount(this.$scope.queryTerms.orderId, this.$scope.queryTerms.clientName, this.$scope.queryTerms.route, this.$scope.queryTerms.shipStartTime,
            this.$scope.queryTerms.shipEndTime,this.orderStatus, "", "", this.$scope.queryTerms.shipAddress, this.$scope.queryTerms.deliverAddress, this.$scope.queryTerms.carCode, this.$scope.queryTerms.contractNumber,
            this.$scope.queryTerms.contractStatus, this.$scope.queryTerms.receiptPriceStatus, this.$scope.queryTerms.oilCardStatus, "", this.TempCustomerServiceOfficerId, "", "", "", this.$scope.queryTerms.driverName, "","","","","").then(res=>{
            this.$scope.gridOptions.totalItems = res.data.extData;
        })
    }


    /**
     * 状态下拉（合同状态下拉，订单状态下拉，油卡状态下拉，回单状态下拉）
     */
    loadStatusDropDown(): void {
        this.$scope.contractStatusDropDown = this.valueService.getContractStatusList().data;
        this.$scope.orderStatusDropDown = this.valueService.getOrderStatusList().data.slice(4, 7);
        this.$scope.oilCardStatusDropDown = this.valueService.getOilCCardStatusList().data;
        this.$scope.receiptPriceStatusDropDown = this.valueService.getReceiptStatusList().data;
    }

    /**
     * 排序
     */
    sortChange = (grid: uiGrid.IGridInstanceOf<carryOrderListResponse>, sortColumns: Array<uiGrid.IGridColumnOf<carryOrderListResponse>>) => {
        if (sortColumns.length == 0) {
            this.reload();
        } else {
            let sortItem = sortColumns[0];
            switch (sortItem.name) {
                case "orderId": {
                    this.orderBy = 1;
                } break;
                case "carryCarCode": {
                    this.orderBy = 2;
                } break;
                case "carLength": {
                    this.orderBy = 3;
                } break;
                case "shipTime": {
                    this.orderBy = 4;
                } break;
                case "startAddress": {
                    this.orderBy = 5;
                } break;
                case "endAddress": {
                    this.orderBy = 6;
                } break;
                case "viaAddress": {
                    this.orderBy = 7;
                } break;
                case "contractNum": {
                    this.orderBy = 8;
                } break;
                case "contractStatus": {
                    this.orderBy = 9;
                } break;
                case "oilCardStatus": {
                    this.orderBy = 10;
                } break;
                case "receiptStatus": {
                    this.orderBy = 11;
                } break;
                case "clientName": {
                    this.orderBy = 12;
                } break;
                case "orderStatus": {
                    this.orderBy = 13;
                } break;
            }
            this.asc = sortItem.sort.direction == "asc";
            this.reload();
        }
    }

    selectChange = (row: uiGrid.IGridRowOf<carryOrderListResponse>) => {
        if (row.isSelected) {
            this.$scope.id = row.entity.id;
            this.$scope.orderInfoList = row.entity;
            this.$scope.carlocation = false;
        }
        else{
            this.$scope.id="";
            this.$scope.carlocation = true;
        }
    }

    /**
     * 监听野狗事件
     */
    onWilddogOrderEvent = (event: ng.IAngularEvent, data: any) => {
        this.query();
    }

    /**
     * 发货单登记事件
     */
    orderRegister = () => {
        if (!this.$scope.id) {
            this.$ngBootbox.alert("最少选择一项");
            return;
        };
        if (this.$scope.orderInfoList.orderList.length > 1) {
            this.$state.go("app.order.orderRegisterBulk", { id: this.$scope.orderInfoList.id, contractStatus: this.$scope.orderInfoList.contractStatus, name: "RegisterBreak", type: this.$scope.orderInfoList.orderList[0].orderStatus,carId:this.$scope.orderInfoList.carId });
        } else {
            this.$state.go("app.order.orderRegisterDetail", { id: this.$scope.orderInfoList.id, contractStatus: this.$scope.orderInfoList.contractStatus, name: "RegisterDetail", type: this.$scope.orderInfoList.orderList[0].orderStatus,carId: this.$scope.orderInfoList.carId});
        };
    }

    /**
     * 应收登记事件
     */
    getRegister = () => {
        if (!this.$scope.id) {
            this.$ngBootbox.alert("最少选择一项");
            return;
        };
        if (this.$scope.orderInfoList.contractNum == null || this.$scope.orderInfoList.contractNum == undefined || this.$scope.orderInfoList.contractNum == "") {
            this.$ngBootbox.alert("未填写合同信息不能应收登记");
            return;
        }
        if (this.$scope.orderInfoList.orderList.length > 1) {
            //零担
            this.$state.go("app.order.orderRegisterReceivableBulk", { id: this.$scope.orderInfoList.id, name: "RegisterBreak" });
        } else {
            //整单
            this.$state.go("app.order.orderRegisterReceivable", { id: this.$scope.orderInfoList.id, name: "register" })
        };
    }

    /**
     * 费用申领事件
     */
    costAplly = () => {
        if (!this.$scope.id) {
            this.$ngBootbox.alert("最少选择一项");
            return;
        }
        if (this.$scope.orderInfoList.orderList[0].isCheckReceivable == false) {
            this.$ngBootbox.alert("应收登记后才能费用申领");
            return;
        }
        if (this.$scope.orderInfoList.contractNum) {
            this.$state.go("app.order.orderCostApplication", { id: this.$scope.orderInfoList.id, name: "costApply" });
        }
        // } else {
        //     this.$ngBootbox.alert("未填写合同信息不能费用申领")
        // }
    }

    /**
     * 定位跟踪事件
     */
    carLbs = () => {
        this.orderService.carryOrder(this.$scope.id).then((res)=>{
            let carId = res.data.carId;
            let carCode = res.data.carCode;
            let phone = res.data.driverPhone;
            let shipAddressL;
            let deliverAddressL;
            if (this.$scope.orderInfoList.orderList.length > 1) {
                shipAddressL = "";
                deliverAddressL = "";
            } else {
                shipAddressL = this.$scope.orderInfoList.orderList[0].startAddress;
                deliverAddressL = this.$scope.orderInfoList.orderList[0].endAddress;
            }
            this.$state.go("app.car.carLocation", { id: carId, carcode: carCode, phone: phone,shipAddress:shipAddressL,deliverAddress:deliverAddressL });
        });   
    }
}

angular.module("tms").controller("orderRegisterController", ["$scope", "valueService", "orderService", "$state", "$ngBootbox", "$location",OrderRegisterController]);